<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="roleQuery">
        <el-form-item>
          <el-input v-model="roleQuery.keyword" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="getRoles">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="pageInfo.list" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column prop="id" label="ID" width="60">
      </el-table-column>
      <el-table-column prop="name" label="部门名称" width="120" sortable>
      </el-table-column>
      <el-table-column prop="sn" label="SN" width="120" sortable>
      </el-table-column>
      <el-table-column label="操作" width="400">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
          <el-button type="warning" size="small" @click="handleAuth(scope.$index, scope.row)">授权</el-button>
          <el-button type="info" size="small" @click="handleMenu(scope.$index, scope.row)">分配菜单</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="roleQuery.currentPage"
          :page-sizes="[3, 5, 10, 20]"
          :page-size="roleQuery.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total"
          style="float:right;">
      </el-pagination>
    </el-col>

    <!--编辑/新增界面-->
    <el-dialog title="编辑/新增" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="editForm">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色介绍" prop="intro">
          <el-input v-model="saveForm.sn" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

    <!--授权界面-->
    <el-dialog title="授权" :visible.sync="authFormVisible" :close-on-click-modal="false">
      <el-form :model="authForm" label-width="80px" ref="editForm">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="authForm.name" disabled auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="授权" prop="sn">
          <el-tree
              :data="permissions"
              show-checkbox
              default-expand-all
              node-key="id"
              ref="tree"
              highlight-current
              :props="defaultProps">
          </el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="authFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="authSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

    <!--分配菜单界面-->
    <el-dialog title="分配菜单" :visible.sync="menuFormVisible" :close-on-click-modal="false">
      <el-form :model="menuForm" label-width="80px" ref="editForm">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="menuForm.name" disabled auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="授权" prop="sn">
          <el-tree
              :data="menus"
              show-checkbox
              default-expand-all
              :check-strictly="true"
              node-key="id"
              ref="menu"
              highlight-current
              :props="defaultProps">
          </el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="menuFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="menuSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
export default {
  data() {
    return {
      // 分页信息
      pageInfo: {
        total: 0,
        list: []
      },
      // 高级查询
      roleQuery: {
        keyword: null,
        currentPage: 1,
        pageSize: 10
      },

      listLoading: false,
      sels: [],//列表选中列

      saveFormVisible: false,//编辑界面是否显示
      editLoading: false, // 编辑页面是否提交中
      authFormVisible:false,// 权限编辑页面是否显示
      menuFormVisible:false,// 菜单分配页面是否显示
      saveFormRules: { // 表单验证规则
        name: [
          {required: true, message: '请输入角色', trigger: 'blur'}
        ]
      },
      //编辑界面数据
      saveForm: {
        id: null,
        name: '',
        sn: ''
      },
      // 权限编辑页面数据
      authForm:{
        id:null,
        name:''
      },
      menuForm:{
        id:null,
        name:'',
        menus:[]
      },
      // 权限列表
      permissions:[],
      menus:[],
      // 上级部门
      roleTree:[],
      // 权限默认配置
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  methods: {
    // 获取已选中的权限
    getCheckedPermissions(id){
      this.$http.get("/role/permissions/"+id)
          .then(result=>{
            result = result.data;
            if (result.success){
              this.$refs.tree.setCheckedKeys(result.data);
            }else{
              this.$message({
                message: result.msg,
                type: 'error'
              });
            }
          })
          .catch(result=>{
            this.$message({
              message: result.data.msg,
              type: 'error'
            });
          })
    },
    // 获得已选中的菜单
    getCheckedMenus(id){
      this.$http.get("/role/menus/"+id)
          .then(result=>{
            result = result.data;
            if (result.success){
              this.$refs.menu.setCheckedKeys(result.data);
            }else{
              this.$message({
                message: result.msg,
                type: 'error'
              });
            }
          })
          .catch(result=>{
            this.$message({
              message: result.data.msg,
              type: 'error'
            });
          })
    },
    // 分页事件
    handleCurrentChange(val) {
      this.roleQuery.currentPage = val;
      this.getRoles();
    },
    handleSizeChange(val) {
      this.roleQuery.pageSize = val;
      this.getRoles();
    },
    //获取部门列表
    getRoles() {
      this.$http.post("/role", this.roleQuery)
          .then(result => {
            this.pageInfo = result.data.data;
          })
          .catch(error => {
            this.$message({
              message: error.data.msg,
              type: 'error'
            });
          })
    },
    // 获取权限列表
    getPermissions(){
      this.$http.put("/permission/tree",this.authForm)
          .then(result => {
            result = result.data;
            if (result.success){
              this.permissions = result.data;
            }else{
              this.$message({
                message: result.msg,
                type: 'error'
              });
            }
          })
          .catch(error => {
            this.$message({
              message: error.data.msg,
              type: 'error'
            });
          })
    },
    // 获取菜单
    getMenus() {
      this.$http.get("/menu/tree")
          .then(result => {
            result = result.data;
            if (result.success){
              this.menus = result.data;
            }else{
              this.$message({
                message: result.msg,
                type: 'error'
              });
            }
          })
          .catch(error => {
            this.$message({
              message: error.data.msg,
              type: 'error'
            });
          })
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        this.$http.delete("/role/" + row.id)
            .then(res => {
              res = res.data
              if (res.success) {
                this.$message({
                  message: '删除成功',
                  type: 'success'
                });
                this.listLoading = false;
                this.roleQuery.currentPage = 1;
                this.getRoles();
              } else {
                this.$message({
                  message: '删除失败',
                  type: 'error'
                });
              }
            })
            .catch(res => {
              this.$message({
                message: res.data.msg,
                type: 'error'
              });
            })
      }).catch(() => {

      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.saveFormVisible = true;
      this.saveForm = Object.assign({}, row);
      // this.$refs['editForm'].resetFields('name');
    },
    //显示新增界面
    handleAdd: function () {
      this.saveFormVisible = true;
      this.saveForm = {
        id: null,
        name: '',
        sn: ''
      };
      // this.$refs['editForm'].resetFields();
    },
    // 点击授权
    handleAuth:function(index,row){
      this.authFormVisible = true;
      this.authForm = Object.assign({}, row);
      // 查询权限列表
      this.getPermissions();
      // 回显已选中
      this.getCheckedPermissions(row.id);
    },
    // 点击分配菜单
    handleMenu:function (index,row) {
      this.menuFormVisible = true;
      this.menuForm = Object.assign({}, row);
      // 查询权限列表
      this.getMenus();
      // 回显已选中
      this.getCheckedMenus(row.id);
    },
    //编辑&新增
    editSubmit: function () {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true;
            this.$http.put("/role", this.saveForm)
                .then(res => {
                  res = res.data;
                  if (res.success) {
                    this.$message({
                      message: '提交成功',
                      type: 'success'
                    });
                    this.saveFormVisible = false;
                    this.editLoading = false;
                    this.roleQuery.currentPage = 1;
                    this.getRoles();
                  } else {
                    this.$message({
                      message: '提交失败',
                      type: 'error'
                    });
                  }
                })
                .catch(res => {
                  this.$message({
                    message: res.data.msg,
                    type: 'error'
                  });
                });
          });
        }
      });
    },
    // 授权提交
    authSubmit:function () {
      var permissions = this.$refs.tree.getCheckedNodes();
      this.authForm.permissions = permissions;
      this.$http.put("/role/saveAuth",JSON.parse(JSON.stringify(this.authForm)))
          .then(result=>{
            result = result.data;
            if (result.success){
              this.authFormVisible = false;
              this.$message({
                message: '授权成功',
                type:'success'
              });
            }else{
              this.$message({
                message: result.msg,
                type:'error'
              });
            }
          })
          .catch(result=>{
            this.$message({
              message: result.data.data.msg,
              type:'error'
            });
          });
    },
    // 分配菜单提交
    menuSubmit:function () {
      this.menuForm.menus = this.$refs.menu.getCheckedNodes();
      this.$http.put("/role/saveMenu",JSON.parse(JSON.stringify(this.menuForm)))
          .then(result=>{
            result = result.data;
            if (result.success){
              this.menuFormVisible = false;
              this.$message({
                message: '授权成功',
                type:'success'
              });
            }else{
              this.$message({
                message: result.msg,
                type:'error'
              });
            }
          })
          .catch(result=>{
            this.$message({
              message: result.data.data.msg,
              type:'error'
            });
          });
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);

      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/role",ids)
           .then(res => {
              res = res.data;
              if (res.success) {
                this.listLoading = false;
                this.$message({
                  message: '删除成功',
                  type: 'success'
                });
                this.roleQuery.currentPage = 1;
                this.getRoles();
              } else {
                this.$message({
                  message: '删除失败',
                  type: 'error'
                });
              }
            })
           .catch(res => {
             this.$message({
               message: res.data.msg,
               type: 'error'
             });
            });
      }).catch(() => {

      });
    }
  },
  mounted() {
    this.getRoles();
  }
}

</script>

<style scoped>

</style>